package com.woniu.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.entity.PageData;
import com.woniu.entity.Result;
import com.woniu.entity.dto.ProductDTO;
import com.woniu.pojo.Product;
import com.woniu.pojo.Training;
import com.woniu.service.ITrainingService;
import com.woniu.service.ProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Api(tags = "商品管理")
@RestController
@RequestMapping("/product")
public class ProductController extends BaseController{

    @Autowired
    private ProductService productService;

    /*查询收藏表并分页*/
    @PostMapping("/searchPage/{currentPage}/{pageSize}")
    @ApiOperation("分页查询")
    public Result searchPage(@PathVariable Integer currentPage,
                             @PathVariable Integer pageSize,
                             @RequestBody ProductDTO productDTO){
        PageData pageData = productService.searchPage(currentPage,pageSize,productDTO);
        return toDataResult(pageData);
    }

    /*新增产品*/
    @PostMapping("/insert")
    @ApiOperation("新增产品")
    public Result increase(@RequestBody Product product){


        return toResult(productService.save(product));
    }

    /*修改产品*/
    @PostMapping("/update")
    @ApiOperation("修改产品")
    public Result revise(@RequestBody Product product){

        return toResult(productService.updateById(product));

    }

    /*单个删除产品*/
    @PostMapping("/deleteById/{id}")
    @ApiOperation("删除产品")
    public Result decrease(@PathVariable Integer id){

        Boolean flag = productService.removeById(id);
        return toResult(flag);

    }

    /*批量删除产品*/
    @PostMapping("/deletePart")
    @ApiOperation("批量删除产品")
    public Result deletePart(@RequestBody List<Integer> ids){
        boolean flag = productService.removeBatchByIds(ids);
        return toResult(flag);
    }

    //修改数据所需的按id查询
    @GetMapping("/searchById/{id}")
    @ApiOperation("按id查询")
    public Result searchById(@PathVariable Integer id){

        Product product = productService.getById(id);
        return toDataResult(product);
    }

    @ApiOperation("导出数据")
    @PostMapping("/export")
    public void exportExcel(@RequestBody(required = false) ProductDTO productDTO,
                            HttpServletResponse response) throws IOException {
        PageData pageData =  productService.searchPage(1, 1000, productDTO);
        List<Product> productList = (List<Product>) pageData.getData();
        EasyExcel.write(response.getOutputStream(), Product.class).sheet().doWrite(productList);
    }
}
